package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.CodeUtil;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.UserInfo;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.app.service.LoginService;
import com.atguigu.lease.web.app.service.SmsService;
import com.atguigu.lease.web.app.service.UserInfoService;
import com.atguigu.lease.web.app.vo.user.LoginVo;
import com.atguigu.lease.web.app.vo.user.UserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private SmsService smsService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private UserInfoService userInfoService;


    // 获取短信验证码的方法
    @Override
    public void getCode(String phone) {
        //1.生成存储到redis的key
        String key = RedisConstant.APP_LOGIN_PREFIX + phone;
        //2.判断redis中是否有key
        Boolean hasKey = redisTemplate.hasKey(key);
        //3.如果有key值存在 说明之前请求了一次验证码
        if (hasKey) {
            //3.1获取Redis当中的过期时间
            Long TTL = redisTemplate.getExpire(key);
            //3.2获取key存活的时间是否超过60秒
            //3.2如果小于60秒则代表一分钟之内以及发送过一条短信，不能继续发送了
            if (RedisConstant.APP_LOGIN_CODE_TTL_SEC - TTL < RedisConstant.APP_LOGIN_CODE_RESEND_TIME_SEC) {
                //3.3如果小于60秒 则直接响应`验证码发送过于平凡`
                throw new LeaseException(ResultCodeEnum.APP_SEND_SMS_TOO_OFTEN);
            }
        }
        //4.如果key值不存在则生成验证码
        String code = CodeUtil.getRandomCode(6);
        //5.发送验证码
        smsService.sendCode(phone, code);
        //6.存储到redis 并设置过期时间
        redisTemplate.opsForValue().set(key, code, RedisConstant.APP_LOGIN_CODE_TTL_SEC, TimeUnit.SECONDS);
    }

    // 实现登录功能并响应token给前端
    @Override
    public String login(LoginVo loginVo) {
        //1.判断手机号码是否为空
        if (!StringUtils.hasText(loginVo.getPhone())) {
            //响应手机号码为空
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_PHONE_EMPTY);
        }
        //2.判断验证码是否为空
        if (!StringUtils.hasText(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }
        //3.根据手机号码查询之前保存到redis当中的验证码
        String key = RedisConstant.APP_LOGIN_PREFIX + loginVo.getPhone();
        String code = redisTemplate.opsForValue().get(key);
        //4.如果查出来的验证码为空，则直接响应验证码已过期
        if (code==null) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EXPIRED);
        }
        //5.判断用户输入的验证码是否正确
        if (!code.equals(loginVo.getCode())) {
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }
        //6.验证码校验结束根据手机号码查询用户是否存在

        LambdaQueryWrapper<UserInfo> userInfoQueryWrapper = new LambdaQueryWrapper<>();
        userInfoQueryWrapper.eq(UserInfo::getPhone, loginVo.getPhone());
        UserInfo userInfo = userInfoService.getOne(userInfoQueryWrapper);
        if (userInfo == null) {
            //6.1如果用户不存在，代表当前用户是第一次登录且注册直接存入数据库当中
            userInfo = new UserInfo();
            userInfo.setPhone(loginVo.getPhone());
            userInfo.setStatus(BaseStatus.ENABLE);
            userInfo.setNickname("用户" + loginVo.getPhone().substring(7));
            userInfoService.save(userInfo);
        }
        //7.如果存在，则判断用户是否被禁用，如果被禁用，则直接响应`账号被禁用`
        if (userInfo.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.APP_ACCOUNT_DISABLED_ERROR);
        }
        //8.生成token
        return JwtUtil.createToken(userInfo.getId(), userInfo.getPhone());

    }

    @Override
    public UserInfoVo getUserInfoById(Long userId) {
        UserInfo user = userInfoService.getById(userId);
        UserInfoVo userInfoVo = new UserInfoVo(user.getNickname(), user.getAvatarUrl());
        return userInfoVo;
    }
}
